const vscode = require('vscode');
const {TecoDebugSession} = require('./TecoDebugSession');
function activateTecoDebug(context, factory) {
    const provider = new TecogdbConfigurationProvider();
    context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('tecogdb', provider));
    context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('tecogdb',{
        provideDebugConfigurations(folder) {
            return [
                {
                    name : "Dynamic Launch",
                    request:"launch",
                    type:"tecogdb",
                    program:"${file}"
                },{
                    name: "tecogdb Launch",
					request: "launch",
					type: "tecogdb",
					program: "${file}"
                }
            ];
        }
    }, vscode.DebugConfigurationProviderTriggerKind.Dynamic));
    if (!factory) {
        factory = new InlineDebugAdapterFactory();
    }
    context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory('tecogdb', factory));
    if ('dispose' in factory) {
        context.subscriptions.push(factory);
    }
}

class TecogdbConfigurationProvider {

    type;
    assetProvider;
    constructor(assetProvider, type) {
        this.assetProvider = assetProvider;
        this.type = type;
    }
    resolveDebugConfiguration(folder, config, token) {

        // if launch.json is missing or empty
        if (!config.type && !config.request && !config.name) {
                config.type = 'tecogdb';
                config.name = 'Launch';
                config.request = 'launch';
                config.program = '${workspaceFolder}/${command:AskForProgramName}';
                config.stopOnEntry = true;
        }

        // if (!config.program) {
        //     return vscode.window.showInformationMessage("Cannot find a program to debug").then(_ => {
        //         return undefined;    // abort launch
        //     });
        // }

        return config;
    }
}

function pathToUri(path) {
	try {
		return vscode.Uri.file(path);
	} catch (e) {
		return vscode.Uri.parse(path);
	}
}

const workspaceFileAccessor = {
    isWindows: false,
    async readFile(path) {
        let uri;
        try {
            uri = pathToUri(path);
        } catch (e) {
            return new TextEncoder().encode(`cannot read '${path}'`);
        }

        return await vscode.workspace.fs.readFile(uri);
    },
    async writeFile(path, contents) {
        await vscode.workspace.fs.writeFile(pathToUri(path), contents);
    }
};


class InlineDebugAdapterFactory {
	createDebugAdapterDescriptor(_session) {
        const session = new TecoDebugSession(workspaceFileAccessor);
		return new vscode.DebugAdapterInlineImplementation(session);
	}
}

module.exports = {activateTecoDebug}